package com.qf.controller;

import com.qf.config.ReidsLockUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class KillController {
    public static Map<String,Integer> itemStock=new HashMap<>();
    public static Map<String,Integer> itemOrder=new HashMap<>();

    @Autowired
    private CuratorFramework cf;
    @Autowired
    private ReidsLockUtil lockUtil;
    static {
        itemStock.put("牙刷",10000);
        itemOrder.put("牙刷",0);
    }

    @RequestMapping("/kill")
    public String kill1(String item)throws Exception{
        InterProcessMutex lock = new InterProcessMutex(cf, "/lock");
        if (lock.acquire(1, TimeUnit.SECONDS)) {

//        if (lockUtil.lock(item,String.valueOf(System.currentTimeMillis()),1)){
            Integer stock = itemStock.get(item);
            if (stock <= 0) {
                return "库存不足";
            }
            itemStock.put(item, stock - 1);

            itemOrder.put(item, itemOrder.get(item) + 1);
            lock.release();
//            lockUtil.unlock(item);
            return "库存还有" + itemStock.get(item) + "单；已下订单" + itemOrder.get(item) + "单。";
        }else {
            return "库存不足！";
        }
    }
}
